package com.lambkit.module.center.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.jfinal.kit.FileKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.lambkit.common.util.ImageUtils;
import com.lambkit.db.mgr.MgrTable;
import com.lambkit.db.sql.column.Example;
import com.lambkit.db.sql.condition.ConditionBuilder;
import com.lambkit.db.sql.condition.SqlBuilder;
import com.lambkit.module.meta.model.MetaImage;
import com.lambkit.module.meta.model.MetaImageSet;
import com.lambkit.module.meta.model.sql.MetaImageCriteria;
import com.lambkit.module.meta.service.MetaImageService;
import com.lambkit.web.controller.LambkitController;

public class ImageController extends LambkitController {

	/**
	 * 获取某一doc的信息
	 */
	public void index() {
		MetaImageService service = MetaImage.service();
		if(service==null) {
			renderJson(Ret.fail().set("msg", "service is null"));
			return;
		}
		MgrTable tbc = getTableView(service.getTableName(), true);
		if (tbc == null) {
			renderJson(Ret.fail().set("msg", "table is not find."));
			return;
		}
		String model_id = getPara(0, getPara("id"));
		if (StrKit.notBlank(model_id)) {
			MetaImage model = service.findById(Long.valueOf(model_id));
			renderJson(Ret.ok().set("data", model));
		} else {
			renderJson(Ret.fail().set("msg", "id is null"));
		}
	}
	
	public void first() {
		Long model_id = getParaToLong(0, getParaToLong("id"));
		if (model_id!=null) {
			MetaImage image = MetaImage.service().findFirst(
					MetaImageCriteria.create().andSidEqualTo(model_id));
			if(image!=null && StrKit.notBlank(image.getPath())) {
				String filePath = image.getPath();
				filePath = filePath.substring(0, filePath.lastIndexOf("."));
				filePath = filePath + "_200x200" + image.getSuffix();
				redirect(getRequest().getContextPath() + filePath);
				return;
			}
		}
		redirect(getRequest().getContextPath() + "/static/atlas/images/pic-none.png");
	}

	/**
	 * 获取doc列表
	 */
	public void list() {
		MetaImageService service = MetaImage.service();
		if(service==null) {
			renderJson(Ret.fail().set("msg", "service is null"));
			return;
		}
		MgrTable tbc = getTableView(service.getTableName(), true);
		if (tbc == null) {
			renderJson(Ret.fail().set("msg", "table is not find."));
			return;
		}
		if(!hasUser()) {
			renderJson(Ret.fail().set("msg", "user is not login."));
			return;
		}
		Long userId = Long.valueOf(getUser().getId().toString());
		Example example = MetaImageCriteria.create()
				.andSidEqualTo(getParaToLong("sid"))
				.andUserIdEqualTo(userId).example();
		renderJson(Ret.ok().set("data", MetaImage.service().find(example, 200)));
	}

	/**
	 * 获取doc列表
	 */
	public void page() {
		MetaImageService service = MetaImage.service();
		if(service==null) {
			renderJson(Ret.fail().set("msg", "service is null"));
			return;
		}
		MgrTable tbc = getTableView(service.getTableName(), true);
		if (tbc == null) {
			renderJson(Ret.fail().set("msg", "table is not find."));
			return;
		}
		ConditionBuilder cb = getConditionsSQL(tbc).build("");
		SqlBuilder sb = new SqlBuilder();
		String select = sb.appendSelect(tbc).build();
		String sql = sb.clear().appendFrom(tbc).appendConditions(cb).build();
		Integer pNumber = getParaToInt(1, getParaToInt("pageNum", 1));
		Integer pSize = getParaToInt(0, getParaToInt("numPerPage", 15));
		Page<Record> page = Db.paginate(pNumber, pSize, select, sql, cb.getSqlParas());
		renderJson(Ret.ok().set("data", page));
	}
	
	public void rename() {
		Long id = getParaToLong("id");
		if(id==null) {
			renderJson(Ret.fail().set("msg", "id is null"));
			return;
		}
		String title = getPara("title");
		if(StrKit.isBlank(title)) {
			renderJson(Ret.fail().set("msg", "title is null"));
			return;
		}
		MetaImage file = MetaImage.service().findById(id);
		file.setName(title);
		boolean flag = file.update();
		if(flag) {
			renderJson(Ret.ok());
		} else {
			renderJson(Ret.fail());
		}
	}
	
	/**
	 * 删除file，并移除目录关系
	 */
	public void delete() {
		String ids = getPara("ids");
		if(StrKit.isBlank(ids)) {
			renderJson(Ret.fail().set("msg", "ids is null"));
			return;
		}
		int n = MetaImage.service().deleteByPrimaryKeys(ids);
		if(n > 0) {
			renderJson(Ret.ok().set("num", n));
		} else {
			renderJson(Ret.fail());
		}
	}
	
	/*
	public void move() {
		Long cid = getParaToLong("cid");
		Long pid = getParaToLong("pid");
		String ids = getPara("ids");
		if(cid==null) {
			renderJson(Ret.fail().set("msg", "cid is null"));
			return;
		}
		if(pid==null) {
			renderJson(Ret.fail().set("msg", "pid is null"));
			return;
		}
		if(StrKit.isBlank(ids)) {
			renderJson(Ret.fail().set("msg", "ids is null"));
			return;
		}
		int n = MetaImage.service().moveFile(cid, pid, ids);
		if(n > 0) {
			renderJson(Ret.ok().set("num", n));
		} else {
			renderJson(Ret.fail());
		}
	}
	*/

	
	public void upload() {
		Long imageSetId = getParaToLong("isid");
		if(imageSetId==null) {
			renderJson(Ret.fail("msg", "ImageSet Id is null."));
			return;
		}
		MetaImageSet imageSet = MetaImageSet.service().findById(imageSetId);
		if(imageSet==null) {
			renderJson(Ret.fail("msg", "ImageSet Model is null."));
			return;
		}
		String webRoot = PathKit.getWebRootPath();
		String filepath = new StringBuilder(webRoot).append(File.separator).append("uploadFile").toString();
		// 获取上传的文件
		//getFile一定要放在第一个参数去获取，否则都获取不到参数
		UploadFile uf = getFile("Filedata", filepath);
		String imageName = uf.getFileName();
		String suffix = FileKit.getFileExtension(uf.getFile());
		// 新地址
		String newFilePath = new StringBuilder()
				.append(File.separator).append("attachment")
				.append(File.separator).append("imageset")
				.append(File.separator).append(imageSet.getPath())
				.append(File.separator).append(System.currentTimeMillis())
				.append(suffix).toString();
		
		StringBuilder newFileName = new StringBuilder(webRoot).append(newFilePath);
		File newfile = new File(newFileName.toString());
		if (!newfile.getParentFile().exists()) {
			newfile.getParentFile().mkdirs();
		}
		// 移动及重命名
		uf.getFile().renameTo(newfile);
		try {
			ImageUtils.scale(newFileName.toString(), 200, 200);
		} catch (IOException e) {
			uf.getFile().delete();
			renderJson(Ret.fail("msg", "Create Image thumbnail is fail."));
			return;
		}
		// 拼接文件上传的完整路径uf.getFileName();
		String fileurl = getSystemPath() + newFilePath;
		System.out.println("================fileurl:" + fileurl);
		
		MetaImage image = new MetaImage();
		image.setSid(imageSetId);
		image.setName(imageName);
		image.setPath(newFilePath);
		image.setMimeType(uf.getContentType());
		image.setSuffix(suffix);
		image.setFilesize(uf.getFile().length());
		image.setCreated(new Date());
		boolean flag = image.save();
		
		if(flag) {
			renderJson(Ret.ok("fileUrl", newFilePath).set("fileName", imageName));
		} else {
			uf.getFile().delete();
			renderJson(Ret.fail("msg", "save error."));
		}
	}
}
